package cn.zhj.base.mvp.presenter

import android.util.Log
import cn.zhj.base.mvp.model.TestModel
import cn.zhj.base.entity.SendingBean
import cn.zhj.base.mvp.contract.TestContract
import cn.zhj.base.mvp.ui.base.BaseMoulePresenter
import kotlinx.coroutines.*

/**
 *  presenter里面有view和model的引用
 * 只能调用IModel IView 以及TestContract.Model  TestContract.View里面的方法
 * 要调用其他方法只能强转后再调用
 */
class TestPresenter : BaseMoulePresenter<TestContract.Model, TestContract.View>() {
    val TAG = "thisTestPresenter"
    override fun createModel(): TestContract.Model {
        return TestModel()
    }

    val request: suspend CoroutineScope.() -> SendingBean = {
        mModel.getSendingState("params")
    }

    fun getSendingState(params:String){
       // Log.e(TAG, "执行getSendingState 11 线程id：${Thread.currentThread().id}")

//        launch(coroutineContext){
//            normalRequest(this,
//                {
//                    Log.e(TAG, "执行getSendingState 22 线程id：${Thread.currentThread().id}")
//                    /*//此处证明协程的上下文确实被activity绑定了，退出activity时，协程结束了。打印结束了
//                    repeat(10){
//                        delay(1000)
//                        Log.e(TAG, "执行getSendingState 2000 线程id：${Thread.currentThread().id}")
//                    }*/
//                    mModel.getSendingState("params")
//                } ,
//                { resp: SendingBean? -> handle(resp)},
//                { errMsg:String ->
//                    run {
//                        Log.e(TAG, "执行getSendingState 44 线程id：${Thread.currentThread().id}")
//                        mRootView?.showMessage(errMsg)
//                    }
//                }
//            )
//        }

//        launch(){
//            normalRequestLoading(mRootView,this,
//                {
//                    Log.e(TAG, "执行getSendingState 22 线程id：${Thread.currentThread().id}")
//                    /*//此处按返回键 证明协程的上下文确实被activity绑定了，退出activity时，协程结束了。打印结束了
//                    repeat(10){
//                        delay(1000)
//                        Log.e(TAG, "执行getSendingState 2000 线程id：${Thread.currentThread().id}")
//                    }*/
//                    mModel.getSendingState("params")
//                } ,
//                { resp: SendingBean? -> handle(resp)},
//                { errMsg:String ->
//                    Log.e(TAG, "执行getSendingState 44 线程id：${Thread.currentThread().id}")
//                    mRootView?.showMessage(errMsg)
//                }
//            )
//        }


//        //精简的不带请求弹窗这么写
//        launch{
//            normalRequest(this,
//                { mModel.getSendingState("params")} ,
//                { resp: SendingBean? -> handle(resp)},
//                { exceptionMsg:String ->
//                    mRootView?.showMessage(exceptionMsg)
//                }
//            )
//        }
//
//        //精简的 请求 带弹窗这么写
//        launch{
//            normalRequestLoading(mRootView ,this,
//                { mModel.getSendingState("params")} ,//model请求代码
//                { resp: SendingBean? -> handle(resp)},//处理正常返回
//                { exceptionMsg:String ->
//                    mRootView?.showMessage(exceptionMsg)//处理协程异常
//                }
//            )
//        }

//        launch{
//            var str = ""
//            repeat (5){
//                str = getImage1(str);
//            }
//            Log.d(TAG, "11111 str == $str")
//            //协程内除了asyn都是顺序执行的,上一个指令执行完成，才会执行下面的
//            //withContext主要用于线程切换
//            withContext(Dispatchers.IO){
//                repeat(5){
//                    delay(1000)
//                    str += getImage2()
//                }
//            }
//            Log.d(TAG, "22222 str == $str")
//            withContext(Dispatchers.IO){
//                str += "YYYYY"
//            }
//            Log.d(TAG, "33333 str == $str")
//        }
        startCode()
    }

    /**
     * 模拟发送短信验证码的流程
     */
    fun startCode(){
        launch{
            var time = 10
            val taskTime = async(Dispatchers.Main){
                repeat(10){
                    delay(1000)
                    Log.i(TAG, "验证码倒计时 tid == ${Thread.currentThread().id}")
                    mRootView?.showMessage("" + time--)
                }
            }
            var httpCode = ""
            withContext(Dispatchers.IO){
                httpCode = getHttpCode();
            }
            if(httpCode == "200"){
                Log.i(TAG, "服务器返回200 tid == ${Thread.currentThread().id}")
            }else{
                Log.i(TAG, "服务器返回其他 tid == ${Thread.currentThread().id}")
            }
            Log.i(TAG, "await 之前 tid == ${Thread.currentThread().id}")
            taskTime.await()
            Log.i(TAG, "await 之后 计时结束 tid == ${Thread.currentThread().id}")
            mRootView?.hideLoading()
        }
    }

    /**
     * 在子线程进行的，并且不被async启动的协程阻塞。
     * 和async里面的代码同时运行，，异步
     */
    private suspend fun getHttpCode(): String {
        repeat(5){
            delay(1000)
            Log.i(TAG, "正在请求服务器发送验证码 tid == ${Thread.currentThread().id}")
        }
        return "200"
    }

    private suspend fun getImage1(str:String) :String{
        delay(1000)
        Log.d(TAG, "getImage1... tid == ${Thread.currentThread().id}")
        return str + "1"
    }

    private fun getImage2(): String {
        Log.d(TAG, "getImage2...tid == ${Thread.currentThread().id}")
        return "x"
    }

    private fun handleImage(str: String): String {
        Log.d(TAG, "getImage...")
        return "xxxxxxxxxxx"
    }


    private fun handle(resp: SendingBean?) {
        Log.e(TAG, "执行getSendingState 33 线程id：${Thread.currentThread().id}")

    }

    private fun normalRequest3(globalScope: GlobalScope, sendingState: SendingBean, function: (String) -> Unit, function1: (String) -> Unit) {
    }

    fun  <T> t1(request: suspend CoroutineScope.() -> T){

    }
    var t2 :CoroutineScope.()->Unit = {

    }

}